package com.jiawen.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiawen.bean.Users;
import com.jiawen.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",username);
        Users user = userMapper.selectOne(queryWrapper);

        if(null == user){
          throw new UsernameNotFoundException("用户名不存在！");
        }
        List<GrantedAuthority> roles = AuthorityUtils.commaSeparatedStringToAuthorityList("admins,ROLE_sale");
        return new User(user.getUsername(),new BCryptPasswordEncoder().encode(user.getPassword()),roles);
    }
}
